﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WaterCloud.Code;
using WaterCloud.DataBase;
using WaterCloud.Domain.Entity.STZBManage;

namespace WaterCloud.Service.STZBManage
{
    /// <summary>
    /// 试师区号服务类
    /// </summary>
    public class SsqhService : BaseService<Ssqh>, IDenpendency
    {
        public SsqhService(ISqlSugarClient context) : base(context)
        {
        }

        /// <summary>
        /// 添加试师区号
        /// </summary>
        /// <param name="code">区号</param>
        /// <returns></returns>
        public async Task AddSsqh(string code)
        {
            Ssqh entity = new Ssqh();
            entity.Code = code;
            entity.CreateTime = DateTime.Now;
            await repository.Insert(entity);
        }

        /// <summary>
        /// 获取试师区号列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="keyword">关键词</param>
        /// <returns></returns>
        public async Task<List<Ssqh>> Get_Ssqh_GridJson(SoulPage<Ssqh> pagination, string keyword)
        {
            var data = repository.IQueryable()
               .WhereIF(!string.IsNullOrEmpty(keyword), x => x.Code.Contains(keyword));
            //权限过滤（保证分页参数存在）
            data = GetDataPrivilege("x", "", data);
            return await data.ToPageListAsync(pagination);
        }

        /// <summary>
        /// 删除试师区号数据
        /// </summary>
        /// <param name="ids">数据id，多个值用逗号隔开</param>
        /// <returns></returns>
        public async Task Delete_Ssqh(string ids)
        {
            string[] idArr = ids.Split(',');
            await repository.Delete(x => idArr.Contains(x.Id.ToString()));
        }

        /// <summary>
        /// 根据id获取试师区号数据
        /// </summary>
        /// <param name="id">数据id</param>
        /// <returns></returns>
        public async Task<Ssqh> GetFormJson(int id)
        {
            var data = await repository.IQueryable().Where(x => x.Id == id).FirstAsync();
            return data;
        }

        /// <summary>
        /// 添加或修改试师区号数据
        /// </summary>
        /// <param name="ssqh">参数</param>
        /// <returns></returns>
        public async Task SubmitForm(Ssqh ssqh)
        {
            if (ssqh.Id <= 0)  //添加
            {
                await AddSsqh(ssqh.Code);
            }
            else //修好
            {
                await repository.Db_Context().Updateable(ssqh).UpdateColumns(x => new { x.Code }).ExecuteCommandAsync();
            }
        }

        /// <summary>
        /// 根据区号查询数据条数
        /// </summary>
        /// <param name="code">区号</param>
        /// <returns></returns>
        public async Task<int> Code_CX(string code)
        {
            var data = await repository.IQueryable().Where(x => x.Code == code).CountAsync();
            return data;
        }
    }
}
